package gotnames.web.st;

import gotnames.Utils;
import gotnames.email.InviteEmail;

import java.io.IOException;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.commons.io.IOUtils;

import com.medallia.spider.RenderTask;
import com.medallia.tiny.Encoding;
import com.medallia.tiny.string.StringTemplateBuilder;

/**
 * Task used to initiate creating a new group. The user inputs an email address
 * and an invitation is sent with a link which takes the user to
 * {@link CreateGroupTask}. The link contains both the email address as well as
 * a hash of it plus {@link #SALT} to ensure that each registered group is
 * associated with a working email.
 */
public class RegisterTask extends RenderTask {

	/** The salt value used by {@link #makeEmailToken(String)} */
	private static final String SALT = "zgpo03jn2716teoi";

	/** Create a token for the given email using {@link #SALT} */
	public static String makeEmailToken(String email) {
		return Encoding.md5(SALT + email);
	}
	
	@Input interface Params {
		String email();
	}
	
	@Output interface Values {
		V<String> EMAIL = v();
	}
	
	PostAction action(Params p) {
		String email = p.email();
		if (email != null) {
			try {
				String msgBody = StringTemplateBuilder.t()
					.attr("url", InviteEmail.WEB_URL)
					.attr("email", Utils.urlEscape(email))
					.attr("token", makeEmailToken(email))
					.go(IOUtils.toString(getClass().getResourceAsStream("registrationEmail.st"))).toString();
				
				Properties props = new Properties();
				Session session = Session.getDefaultInstance(props, null);
				Message msg = new MimeMessage(session);
				msg.setFrom(new InternetAddress("noreply@got-names.appspotmail.com", "Got Names?"));
				msg.addRecipient(RecipientType.TO, new InternetAddress(email));
				msg.setSubject("Create new Got Names? group");
				msg.setText(msgBody);

				Transport.send(msg);
				
				System.out.println(msgBody);
				attr(Values.EMAIL, email);
				
				return template("emailSent");
			} catch (MessagingException e) {
				return rawStringUtf8("Failed to send email: " + e.getMessage());
			} catch (IOException e) {
				return rawStringUtf8("Failed to send email: " + e.getMessage());
			}
		} else {
			return null;
		}
	}

	@Override public String getPageTitle() { return "Got Names? registration"; }

}
